<?php namespace App\Services\Oauth\Reg;

use App\Services\Oauth\SC;
use App\Models\Oauth\Members as MembersModel;
use Validator, Lang, Request, Exception;
use App\Services\CsrfValidate;
use App\Services\BaseProcess;

class Process extends BaseProcess
{
    /**
     * 检测post过来的数据
     * 
     * @param string $username 用户名
     * @param string $password 密码
     * @param string $realname 真实姓名
     */
    public function validate($username, $password, $password_confirm, $realname)
    {
        try {
            $this->checkCsrfToken();
        } catch (Exception $e) {
            return $this->setErrorMsg(Lang::get('common.illegal_operation'));
        }

        if($password != $password_confirm) {
            return $this->setErrorMsg(Lang::get('common.password_not_same'));
        }
        
        $data = array( 'username' => $username, 'password' => $password, 'realname' => $realname );
        $rules = array( 'username' => 'required|min:1', 'password' => 'required|min:1', 'realname' => 'required|min:1' );

        $messages = array(
            'username.required' => Lang::get('reg.please_input_username'),
            'username.min' => Lang::get('reg.please_input_username'),
            'password.required' => Lang::get('reg.please_input_password'),
            'password.min' => Lang::get('reg.please_input_password'),
            'realname.required' => Lang::get('reg.please_input_realname'),
            'realname.min' => Lang::get('reg.please_input_realname'),
        );

        $validator = Validator::make($data, $rules, $messages);

        if ($validator->fails()) {
            return $this->setErrorMsg($validator->messages()->first());
        }

        return true;
    }

    /**
     * 增加新的用户
     *
     * @param string $username 用户名
     * @param string $password 密码
     * @param string $realname 真实姓名
     * @return boolean true|false
     * @access public
     */
    public function addUser($username, $password, $realname)
    {
        $memberModel = new MembersModel();

        if($memberModel->getOneUserByName($username)) {
            return $this->setErrorMsg(Lang::get('reg.account_exists'));
        }

        $password = md5($password);

        $data['name'] = $username;
        $data['password'] = $password;
        $data['realname'] = $realname;

        if($memberModel->addUser($data) !== false) return true;

        return $this->setErrorMsg(Lang::get('common.action_error'));
    }

    /**
     * 手动的验证csrftoken
     */
    private function checkCsrfToken()
    {
        $csrf = new CsrfValidate();
        $csrf->tokensMatch();
    }

}